package org.infodavid.common.persistence;

import java.io.Serializable;

/**
 * The Class LockingClient.
 */
@SuppressWarnings({
  "rawtypes"
})
class LockingClient {

  /**
   * The Class LockingThread.
   */
  private static class LockingThread implements Runnable {

    /** The lockable class. */
    private final Class<? extends IPersistentData> lockableClass;

    /** The lockable key. */
    private final Serializable lockableKey;

    /** The manager. */
    private final PersistenceProviderImpl manager;

    /** The type. */
    private final ILockable.ELockType type;

    /** The start time. */
    private final long start = System.currentTimeMillis();

    /**
     * The Constructor.
     * @param pType the p type
     * @param pManager the p manager
     * @param pLockableClass the lockable class
     * @param pLockableKey the lockable key
     */
    public LockingThread(final PersistenceProviderImpl pManager,
        final Class<? extends IPersistentData> pLockableClass, final Serializable pLockableKey,
        final ILockable.ELockType pType) {
      manager = pManager;
      lockableClass = pLockableClass;
      lockableKey = pLockableKey;
      type = pType;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
      PersistenceSession session = null;
      try {
        session = manager.open();
        session.getTransaction().begin();
        final Object data = session.findEntity(lockableClass, lockableKey);
        session.lock((ILockable)data, type);

        while (System.currentTimeMillis() - start < 10000) {
          Thread.sleep(100);
        }

        session.getTransaction().commit();
      }
      catch (final Exception e) {
        e.printStackTrace();
      }
      finally {
        /*
         * try { manager.close(); } catch (Exception e) {}
         */
      }
    }
  }

  /** The manager. */
  private final PersistenceProviderImpl manager;

  /**
   * The Constructor.
   * @throws Exception the exception
   */
  public LockingClient() throws Exception {
    manager = new PersistenceProviderImpl();
  }

  /**
   * New locking thread.
   * @param type the type
   * @param lockableClass the lockable class
   * @param lockableKey the lockable key
   * @return the thread
   */
  public Thread newLockingThread(final Class<? extends IPersistentData> lockableClass,
      final Serializable lockableKey, final ILockable.ELockType type) {
    return new Thread(new LockingThread(manager, lockableClass, lockableKey, type));
  }
}
